package com.example.controller;

import com.example.common.Result;
import com.example.entity.item.Category;
import com.example.entity.item.Items;
import com.example.entity.item.dto.FreeWithItemDTO;
import com.example.entity.item.itemList;
import com.example.entity.item.item_images;
import com.example.service.FarmerService;
import com.example.service.UserService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/item")
public class ItemController {

    @Resource
    private UserService userService;

    @Resource
    private FarmerService farmerService;

    //查询所有商品
    @GetMapping("/selectItemAll")
    public Result selectItemAll(){
        List<Items> items=userService.selectItemAll();
        return Result.success(items);
    }

    //ID查询商品图片列表
    @GetMapping("/selectItemUrlById/{itemId}")
    public Result selectItemUrlById(@PathVariable String itemId)
    {
        List<item_images> img=userService.selectItemUrlById(itemId);
        return Result.success(img);
    }

    //查询所有商品分类 <删除>
    @GetMapping("/selectItemListAll")
    public Result selectItemListAll()
    {
        List<itemList> list=userService.selectItemListAll();
        return Result.success(list);
    }

    //ID查询商品
    @GetMapping("/selectItemById/{itemId}")
    public Result selectItemById(@PathVariable String itemId)
    {
        FreeWithItemDTO item=userService.selectItemById(itemId);
        return Result.success(item);
    }

    // 动态获取商品列表
    @GetMapping("/findItemsByCategory")
    public Result findItemsByCategory(
            @RequestParam(value = "categoryId", required = false) String categoryId,
            @RequestParam(value = "typeId", required = false) String typeId,
            @RequestParam(value = "classId", required = false) String classId) {

        List<Items> items = userService.findItemsByCategory(categoryId, typeId, classId);
        return Result.success(items);
    }

    // 动态获取商品列表
    @GetMapping("/findItemsByCategoryWithFree")
    public Result findItemsByCategoryWithFree(
            @RequestParam(value = "categoryId", required = false) String categoryId,
            @RequestParam(value = "typeId", required = false) String typeId,
            @RequestParam(value = "classId", required = false) String classId) {

        List<FreeWithItemDTO> items = userService.findItemsByCategoryWithFree(categoryId, typeId, classId);
        return Result.success(items);
    }

    // 获取分类树形结构
    @GetMapping("/getCategory")
    public ResponseEntity<List<Category>> getCategoryTree() {
        List<Category> categoryTree = userService.getCategoryTree();
        return ResponseEntity.ok(categoryTree);
    }

    // 随机获取几个商品
    @GetMapping("/selectRandomItems")
    public Result selectRandomItems() {
        // 获取所有商品
        List<Items> items = userService.selectItemAll();
        // 打乱商品列表
        Collections.shuffle(items);
        // 选择前 5 个商品
        List<Items> randomItems = items.stream().limit(10).collect(Collectors.toList());

        return Result.success(randomItems);
    }

    @Value("${tencent.cos.accessKey}")
    private String accessKey;

    @Value("${tencent.cos.secretKey}")
    private String secretKey;

    @Value("${tencent.cos.region}")
    private String region;

    @Value("${tencent.cos.bucket}")
    private String bucket;

    @Value("${fileBaseUrl}")
    private String fileBaseUrl;

    //商品发布
    @PostMapping("/ItemUpload")
    public Result ItemUpload(@RequestParam("file") MultipartFile file,
                             @RequestParam("itemName") String itemName,
                             @RequestParam("itemPrice") String itemPrice,
                             @RequestParam("itemStock") String itemStock,
                             @RequestParam("itemDesc") String itemDesc,
                             @RequestParam("itemCategory") String itemCategory,
                             @RequestParam("itemType") String itemType,
                             @RequestParam("itemClass") String itemClass)
    {
        String fileName=file.getOriginalFilename();
        System.out.println(fileName+"-"+itemName+"-"+itemPrice+"-"+itemStock+"-"+itemDesc+"-"+itemCategory+"-"+itemType+"-"+itemClass);

        String ItemId=farmerService.selectNewItemId(itemCategory);

        String key="/商品列表/List/"+ItemId+".jpg";
        farmerService.JoinItem(ItemId,itemName,itemPrice,itemStock,itemDesc);
        farmerService.JoinItemList(ItemId,itemName,itemCategory,itemType,itemClass);

        try {
            // 初始化用户身份信息(secretId, secretKey)
            BasicCOSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
            // 设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 生成cos客户端
            COSClient cosClient = new COSClient(cred, clientConfig);

            //创建ObjectMetadata
            ObjectMetadata metadata=new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file.getInputStream(), metadata);
            // 上传文件
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // 关闭客户端
            cosClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件上传到COS失败");
        }
        return Result.success();
    }
}
